// pages/login/login.js
let md5 = require('../../utils/md5');
var app = getApp();
let urlIp = app.globalData.urlIp;
var ctx;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    username: "",
    password: "",
    input: "",
    errorCount: 0,
    checkCode: '',// 验证码
    text: '',
    jugeCode: false, //判定验证码是否隐藏
  },
  watchInput(e) {
    let juge = this.data.input
    if (e.detail.value != juge) {
      this.setData({
        password: ""
      })
    }
    this.data.input = e.detail.value
  },
  submit(e) {
    let obj = e.detail.value
    let self = this;
    let errorCount = wx.getStorageSync("errorCount");
    let { checkCode } = this.data
    let temp = {}
    temp.id = obj.username;
    // 开启校检
    if (obj.username == "") {
      wx.showToast({
        title: "请输入用户名",
        icon: 'error',
        duration: 2000
      })
      return;
    }
    if (obj.password == "") {
      wx.showToast({
        title: "请输入密码",
        icon: 'error',
        duration: 2000
      })
      return;
    }
    if (errorCount > 2) {
      if (e.detail.value.checkCode !== checkCode) {
        wx.showToast({
          title: "验证码错误",
          icon: 'error',
          duration: 2000
        })
        // 初始化验证码
        this.initCode()
        return;
      }
    }

    let mdDate = md5(e.detail.value.password);
    obj.password = mdDate;
    this.axios.add("Session", obj).then(res => {
      if (res.code == '200') {
        wx.setStorageSync("userid", res.data.user.id); //设置userid
        wx.setStorageSync("token", res.data.token);
        this.axios.custom("User", "own").then(res => {
          if (res.code == '200') {
            //let powers = res.data.funcPermissions;
            if (res.data.path) {
              let hadeUrl = urlIp + res.data.path;
              wx.setStorageSync("headUrl", hadeUrl);
            }
            // 缓存用户
            wx.setStorageSync('cacheName',obj.username);
            wx.setStorageSync("errorCount", 0);
            //self.$server().items(powers ? powers : null);
            wx.setStorageSync("power", res.data.funcPermissions);
            wx.setStorageSync("username", res.data.username);
            wx.setStorageSync("customerId", res.data.customerId);
            wx.setStorageSync("customerName", res.data.customerName);
            wx.setStorageSync("customerCode", res.data.customerCode);
            wx.setStorageSync("identity", res.data.typeName);
            wx.setStorageSync("personName", res.data.personName);
            wx.setStorageSync("area", res.data.area);
            wx.setStorageSync("station", res.data.station);
            wx.setStorageSync("phone", res.data.phone);
            wx.setStorageSync("bindWeChat", res.data.bindWeChat);
            wx.switchTab({ url: '/pages/main/index' });

          }
        })

      } else {
        let count = wx.getStorageSync("errorCount")
          ? wx.getStorageSync("errorCount")
          : 0;
        count = Number(count) + 1;
        wx.setStorageSync("errorCount", count);
        if (count > 2) {
          self.setData({
            jugeCode: true
          })
          self.initCode();
        } else {
          self.setData({
            jugeCode: false
          })
        }

        if (count > 9) {
          // 调用锁定API
          this.lockUser(temp);
        } else {

        }
      }
    })
  },
  wxlogin() {
    let self = this;
    wx.login({
      success(res) {
        console.log(res,'登录的code')
        if (res.code) {
          
          //发起网络请求
          self.axios.noToken('WeChat/getAppletUnionId', { code: res.code }, "POST").then((result) => {
            if (result.code == '200') {
              let obj = {};
              obj.tenantId = result.data.openid;
              obj.username = '111';
              obj.password = '222';
              self.axios.add("Session", obj).then(res => {
                if (res.code == '200') {
                  wx.setStorageSync("userid", res.data.user.id); //设置userid
                  wx.setStorageSync("token", res.data.token);
                  self.axios.custom("User", "own").then(res => {
                    if (res.code == '200') {
                      //let powers = res.data.funcPermissions;

                      if (res.data.path) {
                        let hadeUrl = urlIp + res.data.path;
                        wx.setStorageSync("headUrl", hadeUrl);
                      }

                      wx.setStorageSync("errorCount", 0);

                      //self.$server().items(powers ? powers : null);
                      wx.setStorageSync("power", res.data.funcPermissions);
                      wx.setStorageSync("username", res.data.username);
                      wx.setStorageSync("customerId", res.data.customerId);
                      wx.setStorageSync("customerName", res.data.customerName);
                      wx.setStorageSync("customerCode", res.data.customerCode);
                      wx.setStorageSync("identity", res.data.typeName);
                      wx.setStorageSync("personName", res.data.personName);
                      wx.setStorageSync("area", res.data.area);
                      wx.setStorageSync("station", res.data.station);
                      wx.setStorageSync("phone", res.data.phone);
                      wx.setStorageSync("bindWeChat", res.data.bindWeChat);
                      wx.switchTab({ url: '/pages/main/index' });

                    }
                  })
                }
              })
            }

            console.log(re,'请求参数')
          })
        } else {

        }
      }
    })
  },
  change() {
    this.initCode();
  },
  // 生成验证码
  initCode() {
    var that = this;
    this.drawPic(that);
  },

  /**绘制验证码图片**/
  drawPic(that) {
    ctx = wx.createCanvasContext('canvas');
    /**绘制背景色**/
    ctx.fillStyle = this.randomColor(180, 240); //颜色若太深可能导致看不清
    ctx.fillRect(0, 0, 150, 28)
    /**绘制文字**/
    var arr;
    var text = '';
    var str = 'ABCEFGHJKLMNPQRSTWXY123456789';
    for (var i = 0; i < 6; i++) {
      var txt = str[this.randomNum(0, str.length)];
      ctx.fillStyle = this.randomColor(50, 160); //随机生成字体颜色
      ctx.font = this.randomNum(20, 26) + 'px SimHei'; //随机生成字体大小
      var x = 5 + i * 20;
      var y = this.randomNum(20, 25);
      var deg = this.randomNum(-20, 20);
      //修改坐标原点和旋转角度
      ctx.translate(x, y);
      ctx.rotate(deg * Math.PI / 180);
      ctx.fillText(txt, 5, 0);
      text = text + txt;
      //恢复坐标原点和旋转角度
      ctx.rotate(-deg * Math.PI / 180);
      ctx.translate(-x, -y);
    }
    /**绘制干扰线**/
    for (var i = 0; i < 4; i++) {
      ctx.strokeStyle = this.randomColor(40, 180);
      ctx.beginPath();
      ctx.moveTo(this.randomNum(0, 90), this.randomNum(0, 28));
      ctx.lineTo(this.randomNum(0, 90), this.randomNum(0, 28));
      ctx.stroke();
    }
    /**绘制干扰点**/
    for (var i = 0; i < 20; i++) {
      ctx.fillStyle = this.randomColor(0, 255);
      ctx.beginPath();
      ctx.arc(this.randomNum(0, 90), this.randomNum(0, 28), 1, 0, 2 * Math.PI);
      ctx.fill();
    }
    ctx.draw(false, function () {
      console.log(text)
      that.setData({
        text: text,
        checkCode: text
      })
    })

  },
  randomColor(min, max) {
    let r = this.randomNum(min, max);
    let g = this.randomNum(min, max);
    let b = this.randomNum(min, max);
    return 'rgb(' + r + ',' + g + ',' + b + ')';
  },
  randomNum(min, max) {
    return Math.floor(Math.random() * (max - min) + min)
  },
  // 锁定用户
  lockUser(data) {
    var api = "handle/userLock";
    this.axios.noToken(api, data, 'POST').then((res) => {
      if (res.code == "200") {
        wx.setStorageSync("errorCount", 4);
        wx.showToast({
          title: "用户已锁定",
          icon: 'error',
          duration: 2000
        })
      } else {

      }

      console.log(res, "锁定用户");
    });
  },
  // 找回密码
  toBackWord() {
    this.Router.push('backWord');
  },
  _wxValidate() {

  },
  _getUser(data) {

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let username = wx.getStorageSync('cacheName')
    let count = wx.setStorageSync("errorCount");
    if (count && count > 2) {

      this.setData({
        jugeCode: true
      })
      this.initCode()
    } else {
      this.setData({
        jugeCode: false
      })
    }
    if(username){
      this.setData({
        username:username
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})